import React, { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
import { Dictionary } from '../utils/interface';
import usePickerProps from './hooks/use-picker-props';
import { PickerMultiProps, PickerMultiRef, PickerValue } from './interface';
import PickerColumn, { PickerColumnRef } from './PickerColumn';
import PickerContainer from './PickerContainer';

const PickerMulti = forwardRef<PickerMultiRef, PickerMultiProps>(
	(_props, ref) => {
		const [
			{ optionHeight, visibleOptionsCount, transitionDuration },
			{
				defaultValue,
				data: _data,
				dataNames,
				onChange,
				onConfirm,
				onCancel,
				...restProps
			},
		] = usePickerProps(_props);

		const rootRef = useRef<HTMLDivElement>(null);
		const columnRefs = useRef<Dictionary<PickerColumnRef | null>>({});

		const data = useMemo(
			() => (Array.isArray(_data) ? _data : []),
			[_data],
		);

		const pickerMultiRef = useMemo<PickerMultiRef>(
			() => ({
				root: rootRef.current,
				getValue: () => {
					const value: Array<PickerValue | undefined> = [];

					for (let i = 0; i < data.length; i++) {
						const cr = columnRefs.current[i];
						value.push(cr ? cr.getValue() : undefined);
					}

					return value;
				},
			}),
			[data.length],
		);

		useImperativeHandle<PickerMultiRef, PickerMultiRef>(
			ref,
			() => pickerMultiRef,
			[pickerMultiRef],
		);

		const emit = (
			listener?: (v: Array<PickerValue | undefined>) => void,
		) => {
			listener && listener(pickerMultiRef.getValue());
		};

		return (
			<PickerContainer
				{...restProps}
				optionHeight={optionHeight}
				visibleOptionsCount={visibleOptionsCount}
				ref={rootRef}
				onConfirm={() => emit(onConfirm)}
				onCancel={() => emit(onCancel)}
			>
				{data.map((item, idx) => {
					return (
						<PickerColumn
							key={idx}
							optionHeight={optionHeight}
							visibleOptionsCount={visibleOptionsCount}
							transitionDuration={transitionDuration}
							defaultValue={defaultValue && defaultValue[idx]}
							data={item}
							dataNames={dataNames}
							onChange={() => emit(onChange)}
							ref={(ref) => {
								columnRefs.current[idx] = ref;
							}}
						/>
					);
				})}
			</PickerContainer>
		);
	},
);

PickerMulti.displayName = 'PickerMulti';

export default PickerMulti;
